package com.appleyk.sso.service;

import com.appleyk.sso.dao.entity.PurviewDto;
import com.appleyk.sso.dao.entity.UserDto;
import com.appleyk.sso.dao.repo.PurviewRepo;
import com.appleyk.sso.dao.repo.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>越努力，越幸运</p>
 * 自定义加载用户业务类
 * @author appleyk
 * @version V.0.1.1
 * @blob https://blog.csdn.net/appleyk
 * @date created on  9:17 下午 2021/1/10
 */
@Service
public class CustomUserService implements UserDetailsService {

    @Autowired
    private UserRepo userRepo;

    @Autowired
    private PurviewRepo purviewRepo;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        UserDto userDetail = userRepo.findByUserName(userName);
        if (userDetail == null){
            // 如果用户查不到，返回null，交给security自己判断
            return null;
        }

        // 查权限
        List<PurviewDto> purviews = purviewRepo.findPurviewsByUid(userDetail.getId());
        return User.withUsername(userDetail.getUserName())
                .password(userDetail.getPassword())
                .authorities(list2Array(purviews)).build();
    }

    private String[] list2Array(List<PurviewDto> purviewDtos){
        List<String> purviewList = new ArrayList<>();
        purviewDtos.forEach(p->purviewList.add(p.getCode()));
        String[] purviewArray = new String[purviewList.size()];
        purviewList.toArray(purviewArray);
        return purviewArray;
    }
}
